package com.google.code.chaotic.updates;

import javax.jdo.PersistenceManager;

import org.restlet.resource.ClientResource;
import org.restlet.resource.Get;
import org.restlet.resource.Put;
import org.restlet.resource.ServerResource;

import com.google.code.chaotic.model.AppProperty;
import com.google.code.chaotic.server.PmFactory;

/**
 * Resource which has only one representation.
 * 
 */
public class FrontTierStarterResourceImpl extends ServerResource //
		implements FrontTierStarterResource {

	//

	//

	@Get
	@Override
	public String start() {
		String backTierTierUrl = FrontTierUpdatesApp.getBackTierUrl();

		ClientResource clientResource = new ClientResource(//
				backTierTierUrl + "/updates/start");

		BackTierStarterResource backStarter = clientResource
				.wrap(BackTierStarterResource.class);

		return backStarter.start();
	}

	@Put
	@Override
	public void register(BackTierWebInfo info) {
		PersistenceManager pm = PmFactory.get().getPersistenceManager();
		// Transaction tx = pm.currentTransaction();
		try {
			// tx.begin();
			pm.makePersistent(new AppProperty(//
					FrontTierUpdatesApp.KEY_HOST_NAME, //
					info.getHostAddress()));
			pm.makePersistent(new AppProperty(//
					FrontTierUpdatesApp.KEY_APP_PORT, //
					info.getAppPort().toString()));
			pm.makePersistent(new AppProperty(//
					FrontTierUpdatesApp.KEY_CONTEXT_PATH, //
					info.getContextPath()));
			// tx.commit();

		} finally {
			// if (tx.isActive())
			// tx.rollback();
			pm.close();
		}
	}

}